import React, { useState, useEffect, useMemo } from 'react';
import {
    Layout, Form, Input, Button, Select, Table, Modal, Drawer, Card,
    Row, Col, DatePicker, Tag, Divider, message, Popconfirm, TreeSelect
} from 'antd';
import {
    PlusOutlined, SearchOutlined, EditOutlined, DeleteOutlined, EyeOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { Content } = Layout;
const { Option } = Select;

/* -------- 模拟数据（已调整类型以保持一致性） -------- */
const userMap = {
    1: '张三',
    2: '李四',
    3: '王五',
};
const SupplierTreeData = [
    {
        title: '供应商',
        key: 1,
        value: 1,
        children: [
            { title: '钢筋供应商', key: 2, value: 2 },
            {
                title: '水泥供应商',
                key: 3,
                value: 3,
                children: [
                    { title: '建筑水泥供应商', key: 6, value: 6 },
                    { title: '家用水泥供应商', key: 7, value: 7 },
                ],
            },
        ],
    },
    {
        title: '五金材料供应商',
        key: 8,
        value: 8,
        children: [
            { title: '螺丝供应商', key: 9, value: 9 },
            { title: '螺帽供应商', key: 10, value: 10 },
        ],
    }
];

const MaterialsTypeTreeData = [
    {
        title: '建设材料',
        key: 1,
        value: 1,
        children: [
            { title: '钢筋', key: 2, value: 2 },
            {
                title: '水泥',
                key: 3,
                value: 3,
                children: [
                    { title: '建筑水泥', key: 6, value: 6 },
                    { title: '家用水泥', key: 7, value: 7 },
                ],
            },
        ],
    },
    {
        title: '五金材料',
        key: 8,
        value: 8,
        children: [
            { title: '螺丝', key: 9, value: 9 },
            { title: '螺帽', key: 10, value: 10 },
        ],
    },
];

const mockSupplier = [
    { id: 1, name: '供应商A', type: 2 },
    { id: 2, name: '供应商B', type: 3 },
    { id: 3, name: '供应商C', type: 9 },
];

const mockMaterials = [
    {
        id: 1,
        name: '钢筋',
        code: 'MAT-001',
        specification: 'Φ20mm',
        supplier: 1,
        project: 1,
        warehouse: 101,
        type: 2,
        purchaseTime: '2023-06-01',
        paymentTime: '2023-06-15',
        cost: 4800,
        unit: '吨',
        rate: 0.13,
        status: 4,
        purchaser: 1,
        remark: '优质钢材，用于主体结构',
        unit_price:30,
        amount_change: {
            "purchase": {
                "description": "采购入库",
                "date": "2023-06-01",
                "amount": 1500
            },
            "consumption": {
                "description": "日常生产领用",
                "date": "2023-06-01",
                "amount": 350
            },
            "transfer": {
                "description": "从A仓调拨至B仓",
                "date": "2023-06-02",
                "amount": 200
            },
            "sales": {
                "description": "对外销售",
                "date": "2023-06-03",
                "amount": 300
            },
            "rental": {
                "description": "客户短期租借",
                "date": "2023-06-04",
                "amount": 100
            },
            "loss": {
                "description": "运输及存储损耗",
                "date": "2023-06-05",
                "amount": 50
            },
            "restitution": {
                "description": "客户短期租借归还",
                "date": "2023-06-05",
                "amount": 100
            },
        },
    }
];

const mockProjects = [
    { id: 1, name: '上海中心大厦项目' },
    { id: 2, name: '杭州湾跨海大桥项目' }
];

const mockWarehouses = [
    { id: 101, name: '主材料仓库', projectId: 1 },
    { id: 102, name: '电气仓库', projectId: 1 },
    { id: 103, name: '装饰材料仓库', projectId: 1 },
    { id: 201, name: '主材料仓库', projectId: 2 },
    { id: 202, name: '桥梁构件仓库', projectId: 2 }
];
const statusMap = {
    1: '在库',
    2: '部分出库',
    3: '已全部出库',
    4: '已作废',
};
/* -------- 组件主体 -------- */
const MaterialsManagement = () => {
    const [form] = Form.useForm();
    const [filterForm] = Form.useForm();
    const [materials, setMaterials] = useState([]);
    const [filteredMaterials, setFilteredMaterials] = useState([]);
    const [projects] = useState(mockProjects);
    const [warehouses, setWarehouses] = useState([]);
    const [selectedProject, setSelectedProject] = useState(null);
    const [selectedWarehouse, setSelectedWarehouse] = useState(null);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isDetailVisible, setIsDetailVisible] = useState(false);
    const [currentMaterial, setCurrentMaterial] = useState(null);
    const [loading, setLoading] = useState(false);
    const [filterValues, setFilterValues] = useState({});

    useEffect(() => {
        setLoading(true);
        // 模拟请求
        setTimeout(() => {
            setMaterials(mockMaterials);
            setLoading(false);
        }, 300);
    }, []);

    // 生成供应商树（分类节点 key/value 都是数字，叶子节点 key/value 加前缀）
    const generateSupplierTreeWithSuppliers = (nodes) => {
        return nodes.map(node => {
            const childrenFromCategories = node.children ? generateSupplierTreeWithSuppliers(node.children) : [];
            const suppliersUnder = mockSupplier
                .filter(s => s.type === node.key)
                .map(s => ({
                    title: s.name,
                    key: `supplier-${s.id}`,   // key 加前缀
                    value: `supplier-${s.id}`, // value 也加前缀
                    isLeaf: true
                }));
            return {
                ...node,
                key: node.key,     // 分类节点 key 保持数字
                value: node.key,   // value 和 key 一致，避免 warning
                children: [...childrenFromCategories, ...suppliersUnder]
            };
        });
    };

    const supplierTreeWithSuppliers = useMemo(() => generateSupplierTreeWithSuppliers(SupplierTreeData), []);

    // 根据项目选择过滤仓库
    useEffect(() => {
        if (selectedProject) {
            const filtered = mockWarehouses.filter(w => w.projectId === selectedProject);
            setWarehouses(filtered);
            setSelectedWarehouse(filtered.length > 0 ? filtered[0].id : null);
        } else {
            setWarehouses([]);
            setSelectedWarehouse(null);
        }
    }, [selectedProject]);

    // 通用过滤逻辑
    useEffect(() => {
        let filtered = [...materials];

        if (selectedProject) {
            filtered = filtered.filter(m => m.project === selectedProject);
        }
        if (selectedWarehouse) {
            filtered = filtered.filter(m => m.warehouse === selectedWarehouse);
        }
        if (filterValues.name) {
            filtered = filtered.filter(m => (m.name || '').includes(filterValues.name));
        }
        if (filterValues.code) {
            filtered = filtered.filter(m => (m.code || '').includes(filterValues.code));
        }
        if (filterValues.type) {
            filtered = filtered.filter(m => m.type === filterValues.type);
        }
        if (filterValues.status) {
            filtered = filtered.filter(m => m.status === filterValues.status);
        }

        setFilteredMaterials(filtered);
    }, [materials, selectedProject, selectedWarehouse, filterValues]);

    // 新增材料
    const handleAddMaterial = () => {
        setCurrentMaterial(null);
        form.resetFields();
        // 设置默认值
        form.setFieldsValue({
            unit: '个',
            cost: 0,
            rate: 0.13,
            status: '在库',
        });
        setIsModalVisible(true);
    };

    // 编辑材料
    const handleEditMaterial = record => {
        setCurrentMaterial(record);
        form.setFieldsValue({
            ...record,
            purchaseTime: record.purchaseTime ? dayjs(record.purchaseTime) : null,
            paymentTime: record.paymentTime ? dayjs(record.paymentTime) : null
        });
        setIsModalVisible(true);
    };

    const handleViewDetail = record => {
        setCurrentMaterial(record);
        setIsDetailVisible(true);
    };

    const handleDeleteMaterial = id => {
        setMaterials(prev => prev.filter(material => material.id !== id));
        message.success('材料记录删除成功');
    };

    const handleSubmit = values => {
        const formattedValues = {
            ...values,
            supplier: String(values.supplier).startsWith('supplier-')
                ? parseInt(String(values.supplier).replace('supplier-', ''), 10)
                : values.supplier,
            purchaseTime: values.purchaseTime ? values.purchaseTime.format('YYYY-MM-DD') : null,
            paymentTime: values.paymentTime ? values.paymentTime.format('YYYY-MM-DD') : null
        };
        if (currentMaterial) {
            setMaterials(prev =>
                prev.map(m =>
                    m.id === currentMaterial.id ? { ...m, ...formattedValues } : m
                )
            );
            message.success('材料更新成功');
        } else {
            const newMaterial = {
                id: Math.max(...materials.map(m => m.id), 0) + 1,
                ...formattedValues,
                project: selectedProject,
                warehouse: selectedWarehouse,
                status: 1,
            };
            setMaterials(prev => [...prev, newMaterial]);
            message.success('材料添加成功');
        }
        setIsModalVisible(false);
        form.resetFields();
    };

    const handleFilter = (values) => {
        setFilterValues(values || {});
    };

    const resetFilter = () => {
        filterForm.resetFields();
        setFilterValues({});
    };

    // helper 查找
    const findProjectName = (id) => {
        const project = mockProjects.find(p => p.id === id);
        return project ? project.name : '';
    };
    const findSupplierName = (id) => {
        const supplier = mockSupplier.find(s => s.id === id);
        return supplier ? supplier.name : id;
    };

    const findTypeName = (key, treeData) => {
        for (const node of treeData) {
            if (node.key === key) {
                return node.title;
            }
            if (node.children) {
                const childResult = findTypeName(key, node.children);
                if (childResult) return childResult;
            }
        }
        return null;
    };

    const columns = [
        { title: '物料编码', dataIndex: 'code', key: 'code', width: 120, fixed: 'left' },
        { title: '物料名称', dataIndex: 'name', key: 'name', width: 150 },
        { title: '规格型号', dataIndex: 'specification', key: 'specification', width: 120 },
        {
            title: '采购人',
            dataIndex: 'purchaser',
            width: 120,
            render: (value) => userMap[value] || value, // 数字映射成名字
        },
        {
            title: '单价', dataIndex: 'unit_price', key: 'unit_price', width: 100,
            render: (text, record) => <span>{text} {record.unit}</span>
        },
        {
            title: '状态', dataIndex: 'status', key: 'status', width: 100,
            render: status => {
                const text = statusMap[status] || '未知';
                const color = { 1: 'green', 2: 'orange', 3: 'blue' }[status] || 'default';
                return <Tag color={color}>{text}</Tag>;
            }
        },
        {
            title: '操作', key: 'action', width: 180, fixed: 'right',
            render: (_, record) => (
                <div>
                    <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>详情</Button>
                    <Button type="link" icon={<EditOutlined />} onClick={() => handleEditMaterial(record)}>编辑</Button>
                    <Popconfirm
                        title="确定要删除此材料吗?"
                        onConfirm={() => handleDeleteMaterial(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="link" icon={<DeleteOutlined />} title="删除" />
                    </Popconfirm>
                </div>
            )
        }
    ];

    return (
        <Layout style={{ height: 'calc(100vh - 64px - 10px)' }}>
            <Content style={{ margin: '16px' }}>
                <Card title="仓库选择" style={{ marginBottom: 16 }}>
                    <Row gutter={16} align="middle">
                        <Col span={8}>
                            <div style={{ marginBottom: 8 }}><strong>选择项目</strong></div>
                            <Select
                                placeholder="请选择项目"
                                onChange={(val) => setSelectedProject(val)}
                                value={selectedProject}
                                style={{ width: '100%' }}
                            >
                                {projects.map(project => (
                                    <Option key={project.id} value={project.id}>{project.name}</Option>
                                ))}
                            </Select>
                        </Col>
                        <Col span={8}>
                            <div style={{ marginBottom: 8 }}><strong>选择仓库</strong></div>
                            <Select
                                placeholder="请选择仓库"
                                onChange={(val) => setSelectedWarehouse(val)}
                                value={selectedWarehouse}
                                style={{ width: '100%' }}
                                disabled={!selectedProject}
                            >
                                {warehouses.map(warehouse => (
                                    <Option key={warehouse.id} value={warehouse.id}>{warehouse.name}</Option>
                                ))}
                            </Select>
                        </Col>
                        <Col span={8} style={{ textAlign: 'right' }}>
                            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddMaterial} disabled={!selectedWarehouse}>
                                新增材料
                            </Button>
                        </Col>
                    </Row>
                </Card>

                <Card title="材料列表" style={{ height: 'calc((100vh - 64px - 24px) * 4 / 5)' }}>
                    <Form form={filterForm} layout="inline" onFinish={handleFilter} style={{ marginBottom: 16 }}>
                        <Form.Item name="name" label="材料名称"><Input placeholder="输入材料名称" /></Form.Item>
                        <Form.Item name="code" label="材料编码"><Input placeholder="输入材料编码" /></Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
                            <Button style={{ marginLeft: 8 }} onClick={resetFilter}>重置</Button>
                        </Form.Item>
                    </Form>

                    <Table
                        columns={columns}
                        dataSource={filteredMaterials}
                        rowKey="id"
                        loading={loading}
                        scroll={{ x: 1300 }}
                        pagination={{ pageSize: 10, showSizeChanger: true, showTotal: total => `共 ${total} 条记录` }}
                    />
                </Card>
            </Content>

            {/* 添加/编辑材料模态框 */}
            <Modal
                title={currentMaterial ? "编辑材料信息" : "新增材料"}
                open={isModalVisible}
                onCancel={() => { setIsModalVisible(false); form.resetFields(); }}
                footer={null}
                width={800}
                destroyOnHidden={ true}
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                    // 初始值（仅在表单第一次挂载时有效，针对新增我们通过 handleAddMaterial 来设置）
                    initialValues={{ unit: '个', cost: 0, rate: 0.13, status: '在库' }}
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="物料编码" name="code" rules={[{ required: true, message: '请输入物料编码' }]}>
                                <Input placeholder="如: MAT-001" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="物料名称" name="name" rules={[{ required: true, message: '请输入物料名称' }]}>
                                <Input placeholder="如: 钢筋" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="规格型号" name="specification" rules={[{ required: true, message: '请输入规格型号' }]}>
                                <Input placeholder="如: Φ20mm" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="材料类型" name="type">
                                <TreeSelect
                                    treeData={MaterialsTypeTreeData}
                                    placeholder="选择材料类型"
                                    allowClear
                                    treeDefaultExpandAll
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="供应商"
                                name="supplier"
                                rules={[
                                    { required: true, message: '请选择供应商' },
                                    {
                                        validator: (_, value) => {
                                            if (!value) return Promise.reject(new Error('请选择供应商'));
                                            const valStr = String(value);
                                            return valStr.startsWith('supplier-')
                                                ? Promise.resolve()
                                                : Promise.reject(new Error('请选择具体供应商（叶子节点），不可选择分类'));
                                        }
                                    }
                                ]}
                            >
                                <TreeSelect
                                    treeData={supplierTreeWithSuppliers}
                                    placeholder="请选择供应商（只能选择叶子节点）"
                                    allowClear
                                    treeDefaultExpandAll
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="单价"
                                name="unit_price"
                                rules={[{ required: true, message: '请输入单价' }]}
                            >
                                <Input type="number" placeholder="如: 30" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="单位" name="unit" rules={[{ required: true, message: '请输入单位' }]}>
                                <Input placeholder="如: 吨" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="采购时间" name="purchaseTime" rules={[{ required: true, message: '请选择采购时间' }]}>
                                <DatePicker style={{ width: '100%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="付款时间" name="paymentTime">
                                <DatePicker style={{ width: '100%' }} />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="采购人员"
                                name="purchaser"
                                rules={[{ required: true, message: '请选择采购人员' }]}
                            >
                                <Select placeholder="请选择采购人员">
                                    {Object.entries(userMap).map(([id, name]) => (
                                        <Select.Option key={id} value={parseInt(id, 10)}>
                                            {name}
                                        </Select.Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="税率" name="rate" rules={[{ required: true, message: '请输入税率' }]}>
                                <Input type="number" step="0.01" placeholder="如: 0.13" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item label="采购成本" name="cost" rules={[{ required: true, message: '请输入采购成本' }]}>
                        <Input type="number" placeholder="如: 4800" />
                    </Form.Item>

                    <Form.Item label="备注" name="remark">
                        <Input.TextArea placeholder="请输入备注信息" rows={3} />
                    </Form.Item>

                    <Form.Item style={{ textAlign: 'right' }}>
                        <Button onClick={() => { setIsModalVisible(false); form.resetFields(); }} style={{ marginRight: 8 }}>取消</Button>
                        <Button type="primary" htmlType="submit">{currentMaterial ? '更新' : '添加'}</Button>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 材料详情抽屉 */}
            <Drawer
                title="材料详细信息"
                width={600}
                open={isDetailVisible}
                onClose={() => setIsDetailVisible(false)}
            >
                {currentMaterial && (
                    <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 24 }}>
                            <Tag color="blue">{currentMaterial.code}</Tag>
                            <Tag color={{1:'green',2:'orange',3:'blue'}[currentMaterial.status] || 'default'}>
                                {statusMap[currentMaterial.status] || '未知'}
                            </Tag>
                        </div>

                        <Card title="基本信息" size="small">
                            <Row gutter={16}>
                                <Col span={12}>
                                    <p><strong>名称：</strong>{currentMaterial.name}</p>
                                    <p><strong>规格型号：</strong>{currentMaterial.specification}</p>
                                    <p>
                                        <strong>类型：</strong>
                                        {currentMaterial.type
                                            ? findTypeName(currentMaterial.type, MaterialsTypeTreeData) || currentMaterial.type
                                            : ''}
                                    </p>
                                </Col>
                                <Col span={12}>
                                    <p><strong>供应商：</strong>{findSupplierName(currentMaterial.supplier)}</p>
                                    <p><strong>采购时间：</strong>{currentMaterial.purchaseTime}</p>
                                    <p><strong>付款时间：</strong>{currentMaterial.paymentTime || '未付款'}</p>
                                </Col>
                            </Row>
                        </Card>

                        <Divider />

                        <Card title="其他信息" size="small">
                            <p><strong>税率：</strong>{currentMaterial.rate ? (currentMaterial.rate * 100) : 0}%</p>
                            <p><strong>备注：</strong>{currentMaterial.remark}</p>
                            <p><strong>单价：</strong>{currentMaterial.unit_price}元</p>
                            <p><strong>所在项目：</strong>{findProjectName(currentMaterial.project)}</p>
                            <p><strong>所在仓库：</strong>{(mockWarehouses.find(w => w.id === currentMaterial.warehouse) || {}).name}</p>
                        </Card>
                    </div>
                )}
            </Drawer>
        </Layout>
    );
};

export default MaterialsManagement;
